import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Modal, Select, Button, Card, Tooltip, Popconfirm } from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';

const { Option } = Select;
const { info, success, warning } = Modal;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const SelectRelaForm = dynamic({
  loader: () => import('./SelectRelaForm'),
  loading: LoadingComponent,
});

const namespace = 'flowTacheConfig';

function RelaForm(props) {
  const [params, setParams] = useState({
    flowNodeId: -999,
  });
  const [selectRelaFormVisible, setSelectRelaFormVisible] = useState(false); // 设置表单弹窗

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp(
    { pageSize: 10 },
    'pmc/pms/pmTacheFormRela/queryPage',
    params
  );

  // 初始化数据
  useEffect(() => {
    if (props.selectRecord !== undefined && !isEmptyObject(props.selectRecord)) {
      setParams({
        flowNodeId: props.selectRecord.flowNodeId === null ? -999 : props.selectRecord.flowNodeId,
      });
    }
  }, [props.selectRecord]);

  const reloadGrid = () => {
    setParams({
      ...params,
    });
  };

  // 设置选择表单模态框控制方法
  const handleSelectRelaFormVisible = visibleFlag => {
    setSelectRelaFormVisible(visibleFlag);
  };
  // 设置选择表单回调处理
  const handleSelectRelaFormCallBack = resData => {
    saveReloadFlag(!props.reloadFlag);
    reloadGrid();
  };
  // 设置选择表单回调方法
  const handleSelectRelaFormCallBackMethods = {
    handleSelectRelaFormVisible,
    handleSelectRelaFormCallBack,
  };

  // 通过dva存当前需要传递的数据
  const saveReloadFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveReloadFlag`,
      payload: params,
    });
  };

  const handleAdd = () => {
    if (!props.selectRecord || isEmptyObject(props.selectRecord)) {
      warning({ content: '请先选择一个环节' });
      return;
    }
    if (tableProps && tableProps.data && tableProps.data.list && tableProps.data.list.length > 0) {
      warning({ content: '已绑定表单，若要绑定新表单，请先删除已绑定表单' });
      return;
    }
    setSelectRelaFormVisible(true);
  };

  const handleRemove = record => {
    request('pmc/pms/pmTacheFormRela/delete', {
      method: 'GET',
      data: {
        tacheFormRelId: record.tacheFormRelId,
      },
    }).then(res => {
      if (res.success && res.success === true) {
        reloadGrid();
      } else {
        info({ title: '删除失败', content: res.errMessage });
      }
    });
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '表单名称',
      dataIndex: 'formName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '版本',
      dataIndex: 'formVersionNbr',
    },
    {
      title: '表单版本描述',
      dataIndex: 'formVersionDesc',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            <Popconfirm
              title="是否删除该表单关联？"
              onConfirm={() => {
                handleRemove(record);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        title="关联表单列表"
        extra={
          <div>
            <Button
              className="margin-left"
              type="primary"
              onClick={() => {
                handleAdd();
              }}
            >
              新增
            </Button>
          </div>
        }
      >
        <SlickTable
          rowKey={record => record.tacheFormRelId}
          columns={columns}
          {...tableProps}
          scroll={{ x: 'max-content' }}
        />
      </Card>
      {selectRelaFormVisible ? (
        <SelectRelaForm
          {...handleSelectRelaFormCallBackMethods}
          modalVisible={selectRelaFormVisible}
        />
      ) : null}
    </div>
  );
}

export default connect(({ flowTacheConfig, setting }) => ({
  reloadFlag: flowTacheConfig.reloadFlag,
  selectRecord: flowTacheConfig.selectRecord,
  size: setting.size,
}))(Form.create()(RelaForm));
